import math  # 导入数学模块

def euclidean_distance(point1, point2):  # 计算欧几里得距离
    return math.sqrt(sum((a - b) ** 2 for a, b in zip(point1, point2)))  # 计算两点间距离

def knn_predict(train_data, train_labels, test_point, k=3):  # K近邻预测函数
    distances = []  # 存储距离的列表
    
    for i, train_point in enumerate(train_data):  # 遍历训练数据
        dist = euclidean_distance(test_point, train_point)  # 计算测试点到训练点的距离
        distances.append((dist, train_labels[i]))  # 存储距离和对应标签
    
    distances.sort(key=lambda x: x[0])  # 按距离从小到大排序
    
    k_nearest = distances[:k]  # 取前k个最近邻
    k_labels = [label for _, label in k_nearest]  # 提取k个最近邻的标签
    
    # 返回出现次数最多的标签
    return max(set(k_labels), key=k_labels.count)  # 统计并返回最多出现的标签

# 测试代码
if __name__ == "__main__":
    # 训练数据：特征
    train_data = [
        [1, 2], [1, 4], [2, 1], [2, 3],  # 类别0
        [5, 6], [6, 5], [7, 7], [6, 8]   # 类别1
    ]
    
    # 训练数据：标签
    train_labels = [0, 0, 0, 0, 1, 1, 1, 1]  # 对应标签
    
    # 测试点
    test_point = [3, 3]  # 待分类的点
    
    # 使用KNN预测
    prediction = knn_predict(train_data, train_labels, test_point, k=3)  # K=3进行预测
    
    print(f"测试点 {test_point} 的预测类别是: {prediction}")  # 输出预测结果